package com.kika.obwiki.service.impl;

import com.kika.obwiki.entity.Category;
import com.kika.obwiki.mapper.CategoryMapper;
import com.kika.obwiki.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kika.obwiki.rep.CategoryQueryReq;
import com.kika.obwiki.rep.CategorySaveReq;
import com.kika.obwiki.resp.CategoryQueryResp;
import com.kika.obwiki.resp.PageResp;
import com.kika.obwiki.utils.CopyUtil;
import com.kika.obwiki.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cr
 * @since 2025-06-22
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private SnowFlake snowFlake;

    /**
     * 根据名称分页查询分类列表
     *
     * @param req 查询参数
     * @return 分页响应
     */
    @Override
    public PageResp<CategoryQueryResp> listByname(CategoryQueryReq req) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(req.getName()), "name", req.getName());
        Page<Category> page = new Page<>(req.getPage(), req.getSize());
        page = this.baseMapper.selectPage(page, queryWrapper);
        PageResp<CategoryQueryResp> pageResp = new PageResp<>();
        pageResp.setList(CopyUtil.copyList(page.getRecords(), CategoryQueryResp.class));
        pageResp.setTotal(page.getTotal());
        return pageResp;
    }

    /**
     * 保存分类信息
     *
     * @param req 保存参数
     */
    @Override
    public void save(CategorySaveReq req) {
        Category category = CopyUtil.copy(req, Category.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            long id = snowFlake.nextId();
            category.setId(id);
            this.baseMapper.insert(category);
        } else {
            this.baseMapper.updateById(category);
        }
    }

    /**
     * 删除分类
     *
     * @param id 分类ID
     */
    @Override
    public void delete(Long id) {
        this.baseMapper.deleteById(id);
    }

    /**
     * 查询所有分类
     */
    @Override
    public List<CategoryQueryResp> all() {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        List<Category> categoryList = this.baseMapper.selectList(queryWrapper);
        return CopyUtil.copyList(categoryList, CategoryQueryResp.class);
    }
}
